package com.ruoyi.framework.config;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

public class CustomPasswordEncoder implements PasswordEncoder {

    private BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

    @Override
    public String encode(CharSequence rawPassword) {

        // 简单判断密码是否看起来已经是加密过的格式（这里以BCrypt加密后的格式特点为例进行简单判断，实际可根据具体加密结果格式优化）
        if (rawPassword!= null && rawPassword.toString().matches("\\$2a\\$[0-9]{2}/.*")) {
            System.out.println(rawPassword.toString()+"eeeeee");
            return rawPassword.toString();
        }
        // 如果没加密，使用BCryptPasswordEncoder进行加密
        return bCryptPasswordEncoder.encode(rawPassword);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
//        System.out.println("match"+rawPassword);
        // 同样先判断密码是否已加密，如果已加密直接比较，否则使用BCryptPasswordEncoder进行匹配验证
        if (encodedPassword.equals(rawPassword.toString())) {
            return true;
        }
        return bCryptPasswordEncoder.matches(rawPassword, encodedPassword);
    }
}
